package com.ftcs.controller.common.service.impl;

import com.ftcs.controller.common.service.EngineService;
import com.ftcs.model.DatabaseDTO;
import com.ftcs.model.PageInfo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ManagementService;
import org.activiti.engine.management.TableMetaData;
import org.activiti.engine.management.TablePage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author changhuafeng
 * @since 2019/8/16
 */
@Slf4j
@Service(value = "engineService")
public class EngineServiceImpl implements EngineService {

    @Autowired
    ManagementService managementService;

    @Override
    public Map<String, Object> getEngineInfo() {
        Map<String, Object> resultMap = Maps.newHashMap();
        Map<String, String> engineProperties = managementService.getProperties();
        resultMap.put("engineProperties", engineProperties);

        Map<String, String> systemProperties = Maps.newHashMap();
        Properties systemProperties11 = System.getProperties();
        Set<Object> objects = systemProperties11.keySet();
        for (Object object : objects) {
            systemProperties.put(object.toString(), systemProperties11.get(object.toString()).toString());
        }
        resultMap.put("systemProperties", systemProperties);
        return resultMap;
    }

    @Override
    public DatabaseDTO getDatabaseInfo(String tableName, int current, int pageSize) {
        // 读取表
        Map<String, Long> tableCount = managementService.getTableCount();
        List<String> keys = new ArrayList<String>();
        keys.addAll(tableCount.keySet());
        Collections.sort(keys);

        TreeMap<String, Long> sortedTableCount = new TreeMap<>();

        for (String key : keys) {
            sortedTableCount.put(key, tableCount.get(key));
        }
        DatabaseDTO databaseDTO = DatabaseDTO.builder().tableCount(sortedTableCount).build();

        // 读取表记录
        if (StringUtils.isNotBlank(tableName)) {
            TableMetaData tableMetaData = managementService.getTableMetaData(tableName);
            databaseDTO.setTableMetaData(tableMetaData);
            PageInfo pageInfo = new PageInfo(current, pageSize);
            int firstRow = (current - 1) * pageSize;
            TablePage tablePages = managementService.createTablePageQuery().tableName(tableName).listPage(firstRow, pageSize);

            databaseDTO.setTableInfo(tablePages.getRows());
            pageInfo.setTotal(Math.toIntExact(tableCount.get(tableName.toUpperCase())));
            databaseDTO.setPageInfo(pageInfo);
        }
        return databaseDTO;
    }
}
